/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-5-27 下午6:11 Created by dwzhang
 */
package com.jade.modules.media.impl;

import java.util.Collection;
import java.util.Date;
import javax.ejb.TransactionAttribute;
import javax.inject.Inject;
import javax.inject.Named;

import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.base.vfile.VFileUtils;
import com.jade.modules.media.CMediaItem;
import com.jade.modules.media.MediaException;
import com.jade.modules.media.MediaItemDao;
import com.jade.modules.media.MediaItemManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

/**
 * 基础媒体资料保存库。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-5-27 下午6:11
 */
//@Named ("module_mediaItemManager")
public class ItemManagerImpl implements MediaItemManager
{
    protected MediaItemDao itemDao;

//    @Inject
    public void setItemDao(@Named ("module_mediaItemDao") MediaItemDao itemDao)
    {
        this.itemDao = itemDao;
    }

    public CMediaItem getItem(long itemId)
    {
        return itemDao.getItem(itemId);
    }

    public CMediaItem getItemByUri(String uri)
    {
        return itemDao.getItemByUri(uri);
    }

    protected void doAdd(CMediaItem item)
            throws MediaException
    {
        if (getItemByUri(item.getUri()) != null) {
            throw new MediaException("err.module.media.uri_conflict", "uri conflict", null, item.getUri());
        }
        item.setCreationDate(new Date());
        itemDao.addItem(item);
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Exception.class)
    public void addItem(Collection<CMediaItem> items)
            throws MediaException
    {
        for (CMediaItem item : items) {
            doAdd(item);
        }
    }


    @TransactionAttribute
    @Transactional (rollbackFor = Exception.class)
    public void addItem(CMediaItem... items)
            throws MediaException
    {
        for (CMediaItem item : items) {
            doAdd(item);
        }
    }

    @TransactionAttribute
    @Transactional (rollbackFor = Exception.class)
    public void removeItem(long... ids)
            throws MediaException
    {
        for (long id : ids) {
            CMediaItem item = getItem(id);
            if (item != null) {
                itemDao.removeItem(item);
                //remove file
                VFileUtils.removeFileQuitely(item.getType(), item.getUri());
            }
        }
    }

    public PagingList<CMediaItem> query(Criteria criteria)
    {
        return itemDao.query(criteria);
    }
}
